package view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import entity.MonthlyCard;
import entity.PassBill;
import main.Main;
import util.Constants;
import util.Validator;

public class EntryJPanel extends JPanel {
	private static final long serialVersionUID = -1464040524610072378L;

	public EntryJPanel(){
        setLayout(null);
        setBorder(BorderFactory.createTitledBorder("入场"));
        initUI();
	}
	
	private void initUI(){
		
		JLabel lab1 = new JLabel("车牌号",SwingConstants.RIGHT);
		lab1.setFont(Constants.font);
		lab1.setBounds(100, 30, 60, 30);
	        
        JTextField lab1input = new JTextField();
        Validator.bind(lab1input,Validator.CARID);
        lab1input.setBounds(165, 30, 120, 30);
                
		JButton btn = new JButton("入场");
		btn.setBounds(165, 90, 60, 30);
		btn.setFont(Constants.font);
		btn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String lab1inputStr = lab1input.getText().trim();

				if (Validator.isEmpty(lab1inputStr)) {
					JOptionPane.showMessageDialog(null, "请输入车牌号！");
					return;
				}
				
				boolean result = false;
				PassBill bill = new PassBill();
				if(bill.checkStock(lab1inputStr)){
					JOptionPane.showMessageDialog(null, "操作失败,系统检测到你已经入场了，请人工入场！");
					return;
				}
				MonthlyCard card = new MonthlyCard();
				if(card.check(lab1inputStr)){
					bill.carId = lab1inputStr;
					bill.parkId = card.parkId;
					bill.type = Constants.MonthlyCard;
					result = bill.entry();
					if (result) {
						JOptionPane.showMessageDialog(null, "操作成功！");
					}else{
						JOptionPane.showMessageDialog(null, "操作失败！");
					}
				}else{
					JDialog dlg = new JDialog(Main.frame, "选择车位", true);
					Main.dlgStack.push(dlg);
					dlg.setSize(800, 600);
					dlg.setLocationRelativeTo(null);
					dlg.add(new SelectParkJPanel(lab1inputStr));
					dlg.validate();
					dlg.addWindowListener(new WindowAdapter() {
			        	@Override
			            public void windowClosing(WindowEvent e) {
			        		if(Main.dlgStack.size() == 1){
			        			Main.dlgStack.pop().dispose();
			        		}
			            }
					});
					dlg.setVisible(true);
				}
			}
		});
		
		add(lab1);
		add(lab1input);
		add(btn);
	}
}
